/**
 * 表格上方筛选条件
 * input 输入框, select 下拉选, rangePicker 时间筛选框
 */
/* eslint-disable */
import {Form, Input, Select, Button, DatePicker,Row,Col,Tag,TreeSelect,InputNumber } from 'antd';
import React, {Component} from 'react';
import moment from 'moment';
import config from '../../config';
import Util from '../../utils/Util';
import CheckItemsInFiltrate from './CheckItemsInFiltrate';
import styles from './Filtrate.less';
const {RangePicker, MonthPicker} = DatePicker;
const FormItem = Form.Item;
const InputGroup = Input.Group;
const { CheckableTag } = Tag;

function disabledDate(current) {
  // 当天以后时间禁选,组件传值   disabledDate:true
  return current && current.valueOf() > Date.now();
}

class Filtrate extends Component {
  state = {
    startValue: null,
    endValue: null,
    endOpen: false,
    params:{},
    checkBtnItems:this.props.checkBtnConfig?this.props.checkBtnConfig.items:[]
  };

  componentDidMount() {
    let t = this;
    t.setState({
      params: t.props.form.getFieldsValue()
    });
  }

  submit() {
    let t = this;
    // Form 组件参数
    let params = t.props.form.getFieldsValue();
    let {submit} = t.props;
    submit(params);
  }

  // 清空 Form 组件输入的内容
  clearForm() {
    let t = this;
    if (this.state.checkBtnItems&&this.state.checkBtnItems.length>0){
      let checkBtnItems = [...this.state.checkBtnItems];
      checkBtnItems.map((item, index) => {
        item.status=false;
      });
      this.setState({
        checkBtnItems
      });
    }
    if (t.props.isMyClear === true) {
      let {myClearBtn} = t.props;
      t.props.form.resetFields();
      myClearBtn();
    } else {
      t.props.form.resetFields();
    }

  }

  // 额外按钮点击事件
  extraBtnClick(btnIndex) {
    let t = this;
    let funNameStr = t.props.extraBtn[btnIndex].funName;
    t.props[funNameStr]();
  }

  // 搜索下方按钮点击事件
  underBtnClick (btnIndex,funName) {
    let t = this;
    if (funName)
     t.props[funName]();
  }

  selectedChange(fun, nextParams, paramName, value) {
    let t = this;
    let params = {};
    params[paramName] = value;
    if (paramName) {
      t.setState({params}, () => {
      });
    }
    if (typeof fun === "function") {
      fun(value);
      if (nextParams)
        t.props.form.setFieldsValue({
          [nextParams]: ''
        })
    }
  }

  // 筛选条件组件change事件
  getChangeValue(value, e) {
    console.log(value);
    let t = this;
    let params = {};
    params[value] = e.target.value;
    t.setState({params});
  }

  onChange = (field, value) => {
    this.setState({
      [field]: value,
    });
  };

  onStartChange = (value) => {
    this.onChange('startValue', value);
  };

  onEndChange = (value) => {
    this.onChange('endValue', value);
  };
  handleStartOpenChange = (open) => {
    if (!open) {
      this.setState({endOpen: true});
    }
  };

  handleEndOpenChange = (open) => {
    this.setState({endOpen: open});
  };
  disabledStartDate = (startValue) => {
    const endValue = this.state.endValue;
    if (!startValue || !endValue) {
      return false;
    }
    return startValue.valueOf() > endValue.valueOf();
  };

  disabledEndDate = (endValue) => {
    const startValue = this.state.startValue;
    if (!endValue || !startValue) {
      return false;
    }
    return endValue.valueOf() <= startValue.valueOf();
  };
  onBlur=(name)=>{
    const params = {};
    let value = this.props.form.getFieldValue(name);
    params[name] = value;
    this.setState({params});
  };
  render() {
    let t = this;
    let { checkBtnItems } = t.state;
    let {items, underItems} = t.props;
    let extraBtn = t.props.extraBtn || [];
    let windowWidth = document.body.clientWidth;
    let {getFieldDecorator} = t.props.form;
    // 是否显示清空按钮 默认显示
    let clearBtnShow = true;
    if (t.props.clearBtn === 'hide') {
      clearBtnShow = false;
    }
    // 是否显示查询按钮 默认显示
    let submitBtnShow = true;
    if (t.props.submitBtn === 'hide') {
      submitBtnShow = false;
    }
    return (
      <div className={this.props.className} style={this.props.style}>
        <Row gutter={18}>
          <Col span={this.props.sub?15:24} style={{height:this.props.height}}>
            <div className={styles.base}>
              {/*<div className={`${styles.base} ${underItems ? styles.hashUnderBtn : ''}`}>*/}
              <div style={{width:'100%'}}>
                <Form layout="inline" key="myForm" >
                  {
                    items.map((item, index) => {
                      if (item.type === 'input') {
                        return (<FormItem label={item.label} key={index} className={item.className} style={item.style} colon={item.colon}>
                          {
                            getFieldDecorator(item.paramName, {
                              initialValue: item.initialValue ? item.initialValue : '',
                              rules: item.rules || null
                            })(
                              <Input style={{width: item.width||windowWidth>1600?180:110}} onChange={t.getChangeValue.bind(t, item.paramName)} size={config.size} placeholder={item.placeholder || "请输入"} disabled={item.disabled} addonAfter={item.after}/>
                            )
                          }
                        </FormItem>)
                      }else if(item.type==='rangeInputNumber'){
                        return (
                          <div style={{width:270,display:'inline-block',margin:0,...item.style}} key={index} className={styles.rangeInput}>
                            <FormItem label={item.label} key={item.paramName1} className={item.className} colon={item.colon}>
                              {
                                getFieldDecorator(item.paramName1, {
                                  initialValue: item.initialValue ? item.initialValue : '',
                                  rules: item.rules || null
                                })(
                                  <InputNumber style={{width: item.width || 60,height:windowWidth>1600?30:'auto',padding:windowWidth>1600?'3px 0':'0 0'}} size={config.size} min={0} max={this.state.params[item.paramName2]-0?this.state.params[item.paramName2]-0:item.max} placeholder={item.placeholder || "请输入"} disabled={item.disabled} addonAfter={item.after} onBlur={this.onBlur.bind(this,item.paramName1)}/>
                                )
                              }
                            </FormItem>
                            <FormItem label={'~'} key={item.paramName2} className={item.className} style={{marginLeft:-50,position:'absolute',}} colon={false}>
                              {
                                getFieldDecorator(item.paramName2, {
                                  initialValue: item.initialValue ? item.initialValue : '',
                                  rules: item.rules || null
                                })(
                                  <InputNumber style={{width: item.width || 60,height:windowWidth>1600?30:'auto',padding:windowWidth>1600?'3px 0':'0 0'}} size={config.size} min={this.state.params[item.paramName1]-0} max={item.max} placeholder={item.placeholder || "请输入"} disabled={item.disabled} addonAfter={item.after} onBlur={this.onBlur.bind(this,item.paramName2)}/>
                                )
                              }
                            </FormItem>
                            <span style={{marginTop:windowWidth>1600?20:15,display:'inline-block',position:'absolute',marginLeft:90}}>{item.unit}</span>
                          </div>
                        )
                      } else if (item.type === 'inputNumber') {
                        return (<FormItem label={item.label} key={index} className={item.className} style={item.style} colon={item.colon}>
                          {
                            getFieldDecorator(item.paramName, {
                              initialValue: item.initialValue ? item.initialValue : '',
                              rules: item.rules || null
                            })(
                              <InputNumber style={{width: item.width || 50,height:'30px',padding:'2px 2px'}} onChange={t.getChangeValue.bind(t, item.paramName)} size={config.size} min={item.min} max={item.max}
                                           placeholder={item.placeholder || "请输入"} disabled={item.disabled} addonAfter={item.after}/>
                            )
                          }
                        </FormItem>)
                      }  else if (item.type === 'select') {
                        return (<FormItem label={item.label} key={index} className={item.className} style={{...item.style}}>
                          {
                            getFieldDecorator(item.paramName, {
                              initialValue: item.initialValue ? item.initialValue : (item.options[0] ? Util.numToString(item.options[0].value) : item.options[0]),
                            })(
                              <Select
                                size={config.size}
                               
                                showSearch
                                mode={item.mode}
                                style={{width: item.width || 110}}
                                optionFilterProp="children"
                                dropdownMatchSelectWidth={t.props.dropdownMatchSelectWidth}
                                onChange={t.selectedChange.bind(t, item.selectChange, item.nextParamName || false, item.paramName)}
                                onSelect={item.onSelect}
                                disabled={item.disabled}
                              >
                                {
                                  item.options.map(option => {
                                    return (
                                      <Select.Option key={option.value}
                                                     value={Util.numToString(option.value)}
                                      >
                                        {option.text}
                                      </Select.Option>

                                    )
                                  })
                                }
                              </Select>
                            )
                          }
                        </FormItem>)
                      } else if (item.type === 'treeSelect'){
                        return(
                          <FormItem  key={item.paramName} label={item.label} colon={item.colon} >
                            {
                              getFieldDecorator(item.paramName, {
                                initialValue: item.initialValue || '',
                                rules: item.rules || []
                              })(
                                <TreeSelect
                                  showSearch={item.showSearch}
                                  treeNodeFilterProp={'title'}
                                  size={config.size}
                                  onChange={item.onChange}
                                  disabled={item.disabled}
                                  treeData={item.options}
                                  style={item.styles||{}}
                                  dropdownStyle={{height:`${item.height}`}}
                                  treeCheckable={item.treeCheckable}
                                  onSelect={item.onSelect}
                                />
                              )}
                          </FormItem>
                        )
                      }else if(item.type === 'span'){
                        return (
                          <span className={styles.afterspan} style={item.style} key={index}>{item.content}</span>
                        );
                      }else if (item.type === 'rangePicker') {

                        let disabled = item.disabledDate ? disabledDate : null;

                        return (<FormItem className={styles['range-picker']} label={item.label} key={index} style={item.style}>
                          {
                            getFieldDecorator(item.paramName, {
                              initialValue: item.initialValue===null?null:(item.initialValue&&item.initialValue.length===2?[moment(item.initialValue[0]),moment(item.initialValue[1])]:[moment().add(-1, 'months'), moment()])
                            })(
                              <RangePicker
                                placeholder={['开始时间','结束时间']}
                                showTime={item.showTime}
                                style={{width:item.width}}
                                format={item.format}
                                size={config.size}
                                disabledDate={disabled}
                                disabled={item.disabled}>
                              </RangePicker>
                            )
                          }
                        </FormItem>)
                      } else if (item.type === 'datePicker') {
                        let disabled = item.disabledDate ? disabledDate : null;
                        return (<FormItem className={styles.datePicker} label={item.label}
                                          key={index}>
                          {
                            getFieldDecorator(item.paramName, {
                              initialValue: item.initialValue ? item.initialValue : null
                            })(
                              <DatePicker size={config.size} disabledDate={disabled} disabled={item.disabled}/>
                            )
                          }
                        </FormItem>)
                      } else if (item.type === 'monthPicker') {
                        return (<FormItem label={item.label}
                                          key={index}>
                          {
                            getFieldDecorator(item.paramName, {
                              initialValue: item.initialValue ? item.initialValue : moment()
                            })(
                              <MonthPicker
                                size={config.size}
                                onChange={t.selectedChange.bind(t, item.selectChange)}
                              />
                            )
                          }
                        </FormItem>)
                      } else if (item.type === 'monthRang') {
                        return (
                          <FormItem label={item.label}
                                    key={index}>
                            {
                              getFieldDecorator(item.paramName, {
                                initialValue: item.initialValue || moment().add(-1, 'months')
                              })(
                                <MonthPicker
                                  allowClear={false}
                                  format="YYYY-MM"
                                  disabledDate={this.disabledStartDate}
                                  value={this.state.startValue}
                                  onChange={this.onStartChange.bind(this)}
                                  onOpenChange={this.handleStartOpenChange.bind(this)}
                                  size={config.size}>
                                </MonthPicker>
                              )
                            }
                            {
                              getFieldDecorator(item.paramName2, {
                                initialValue: item.initialValue || moment()
                              })(
                                <MonthPicker
                                  format="YYYY-MM"
                                  disabledDate={this.disabledEndDate}
                                  onChange={this.onEndChange.bind(this)}
                                  open={this.state.endOpen}
                                  value={this.state.endValue}
                                  onOpenChange={this.handleEndOpenChange.bind(this)}
                                  size={config.size}>
                                </MonthPicker>
                              )
                            }
                          </FormItem>
                        )
                      }else if (item.type === 'selectMultiple') {
                        return (<FormItem label={item.label} key={index}>
                          {
                            getFieldDecorator(item.paramName, {
                              initialValue: [],
                            })(
                              <Select
                                size={config.size}
                                showSearch
                                mode="multiple"
                                optionFilterProp="children"
                              >
                                {
                                  item.options.map(option => {
                                    return (
                                      <Select.Option key={option.value}
                                                     value={Util.numToString(option.value)}
                                      >
                                        {option.text}
                                      </Select.Option>

                                    )
                                  })
                                }
                              </Select>
                            )
                          }
                        </FormItem>)
                      }

                    })
                  }
                  <FormItem className={this.props.btnRight?styles.btnRight:null}>
                    { submitBtnShow &&
                    <Button size={config.size}
                            type="primary"
                            onClick={t.submit.bind(t)}
                            className={styles.button}
                    >
                      查询
                    </Button>
                    }
                    {
                      clearBtnShow &&
                      <Button size={config.size}
                              style={{marginLeft: 10}}
                              type="primary"
                              className={styles.button1}
                              onClick={t.clearForm.bind(t)}
                      >
                        重置
                      </Button>
                    }
                  </FormItem>
                  {
                    extraBtn.map((btn, btnIndex) => {
                      return (
                        <FormItem key={btnIndex}>
                          <Button size={config.size}
                                  type="primary"
                                  className={styles.button}
                                  onClick={t.extraBtnClick.bind(t, btnIndex, btn.funName)}
                          >
                            {btn.name}
                          </Button>
                        </FormItem>
                      )
                    })
                  }
                  {
                    underItems &&
                    <div className={styles.underBtn}>
                      {
                        underItems.map((btn, btnIndex) => {
                          if (btn.type === 'button') {
                            return (
                              <FormItem key={btnIndex}>
                                {
                                  btn.label? `${btn.label} :` :''
                                }
                                {
                                  btn.btnList.map((btns, btnsIndex) => {
                                    return (
                                      <Button key={btnsIndex}
                                              size={config.size}
                                              style={{marginLeft: 20, ...btns.style}}
                                              onClick={t.underBtnClick.bind(t, btnsIndex, btns.funName)}
                                      >
                                        {btns.name}
                                      </Button>
                                    )
                                  })
                                }
                              </FormItem>
                            )
                          }else if (btn.type === 'rangePicker') {

                            let disabled = btn.disabledDate ? disabledDate : null;

                            return (<FormItem className={`${styles['range-picker']} ${btn.className}`} label={btn.label}
                                              key={btnIndex}>
                              {
                                getFieldDecorator(btn.paramName, {
                                  initialValue: btn.initialValue===null?null:[moment().add(-1, 'months'), moment()]
                                })(
                                  <RangePicker
                                    showTime={btn.showTime}
                                    format={btn.format}
                                    size={config.size} disabledDate={disabled}>
                                  </RangePicker>
                                )
                              }
                            </FormItem>)
                          } else if (btn.type === 'treeSelect'){
                            return(
                              <FormItem colon={btn.colon} key={btnIndex} label={btn.label} className={btn.className}>
                                {
                                  getFieldDecorator(btn.paramName, {
                                    initialValue: btn.initialValue || '',
                                    rules: btn.rules || []
                                  })(
                                    <TreeSelect
                                      showSearch={btn.showSearch}
                                      treeNodeFilterProp={'title'}
                                      size={config.size}
                                      onChange={btn.onChange}
                                      disabled={btn.disabled}
                                      treeData={btn.options}
                                      style={btn.styles||{}}
                                      dropdownStyle={{height:200}}
                                      treeCheckable={btn.treeCheckable}
                                      onSelect={btn.onSelect}
                                    />
                                  )}
                              </FormItem>
                            )
                          } else if(btn.type === 'span'){
                            return (
                              <span className={styles.afterspan}>{btn.content}</span>
                            );
                          }else if (btn.type === 'input') {
                            return (<FormItem label={btn.label} key={btnIndex} className={btn.className}>
                              {
                                getFieldDecorator(btn.paramName, {
                                  initialValue: btn.initialValue ? btn.initialValue : '',
                                  rules: btn.rules || null
                                })(
                                  <Input onChange={t.getChangeValue.bind(t, btn.paramName)} size={config.size}
                                         placeholder={btn.placeholder}/>
                                )
                              }
                            </FormItem>)
                          } else if (btn.type === 'select') {
                            return (<FormItem label={btn.label} key={btnIndex}>
                              {
                                getFieldDecorator(btn.paramName, {
                                  initialValue: btn.initialValue ? btn.initialValue : (btn.options[0] ? Util.numToString(btn.options[0].value) : btn.options[0]),
                                })(
                                  <Select
                                    size={config.size}
                                    showSearch
                                    mode={btn.mode}
                                    style={btn.style ? {width: '200px'} : {}}
                                    optionFilterProp="children"
                                    dropdownMatchSelectWidth={t.props.dropdownMatchSelectWidth}
                                    dropdownStyle={btn.styles}
                                    onChange={t.selectedChange.bind(t, btn.selectChange, btn.btn || false, btn.paramName)}
                                  >
                                    {
                                      btn.options.map(option => {
                                        return (
                                          <Select.Option key={option.value}
                                                         value={Util.numToString(option.value)}
                                          >
                                            {option.text}
                                          </Select.Option>

                                        )
                                      })
                                    }
                                  </Select>
                                )
                              }
                            </FormItem>)
                          } else if (btn.type === 'datePicker') {
                            let disabled = btn.disabledDate ? disabledDate : null;
                            return (<FormItem className={btn.className} label={btn.label}
                                              key={btnIndex} >
                              {
                                getFieldDecorator(btn.paramName, {
                                  initialValue: btn.initialValue ? btn.initialValue : null
                                })(
                                  <DatePicker size={config.size} disabledDate={disabled}/>
                                )
                              }
                            </FormItem>)
                          }else if(btn.type==='remind'){
                            return (<FormItem label={btn.label} className={styles.remind}>
                              {
                                getFieldDecorator(btn.paramName, {
                                  initialValue: btn.initialValue ? btn.initialValue : '',
                                  rules: btn.rules || null
                                })(
                                  <Input onChange={t.getChangeValue.bind(t, btn.paramName)} size={config.size}
                                         placeholder={btn.placeholder} disabled={btn.disabled} addonBefore={btn.addonBefore} addonAfter={btn.addonAfter}/>
                                )
                              }
                            </FormItem>);

                          }else if(btn.type==='remindBtn'){
                            return (
                              <Button size={config.size}
                                      style={{marginLeft: 20,marginTop:8}}
                                      type="primary"
                                      className={styles.button}
                                      onClick={btn.remindBtnClick.bind(t)}
                              >
                                确认
                              </Button>
                            )
                          }

                        })
                      }
                    </div>
                  }
                  <div>
                    {t.props.checkBtnShow&&
                    <FormItem label={t.props.checkBtnConfig.label} className ={t.props.checkBtnConfig.className}>
                      <CheckItemsInFiltrate checkBtnItems={checkBtnItems}
                                            checkBtnParamName={t.props.checkBtnConfig.paramName}
                                            onClick={t.props.checkBtnConfig.onClick}
                      />
                    </FormItem>
                    }
                    {
                      t.props.remind&&
                      <FormItem label={t.props.remind.label} className={styles.remind}>
                        {
                          getFieldDecorator(t.props.remind.paramName, {
                            initialValue: t.props.remind.initialValue ? t.props.remind.initialValue : '',
                            rules: t.props.remind.rules || null
                          })(
                            <Input onChange={t.getChangeValue.bind(t, t.props.remind.paramName)} size={config.size}
                                   placeholder={t.props.remind.placeholder} disabled={t.props.remind.disabled} addonBefore={t.props.remind.addonBefore} addonAfter={t.props.remind.addonAfter}/>
                          )
                        }
                      </FormItem>
                    }
                    {
                      t.props.remindBtn &&
                      <Button size={config.size}
                              style={{marginLeft: 20,marginTop:8}}
                              type="primary"
                              className={styles.button}
                              onClick={t.props.remindBtnClick.bind(t)}
                      >
                        确认
                      </Button>
                    }
                  </div>
                </Form>
              </div>

            </div>

          </Col>
          {
            this.props.sub &&
            <Col span={9}>
              <div className={styles.sub} style={this.props.subStyle}>
                {this.props.children}
              </div>
            </Col>
          }
        </Row>
      </div>


    )
  }
}

export default  Form.create()(Filtrate);
